<?php
namespace Api\Model;



class UserVoteModel extends BaseModel {

    private static $instance;

    public static function singleton()
    {
        self::$instance === null and self::$instance = new self();
        return self::$instance;
    }


    //判断用户是否投票
    public function getByUserIdAndRecordId($user_id,$record_id){
        $where['user_id']=$user_id;
        $where['record_id']=$record_id;
        return $this->where($where)->find();
    }

    //投票记录
    public function vote($user_id,$record_id,$rate){
        $data=[
            'user_id'=>$user_id,
            'record_id'=>$record_id,
            'rate'=>$rate,
            'create_at'=>date('Y-m-d H:i:s')
        ];
        return $this->add($data);
    }

    //获取投票总数（比例）
    public function getTotalRateByRecordId($record_id){
        $data = $this->where(['record_id'=>$record_id])->avg('rate');
        $data =round($data);
        return $data;
    }

    //获取投票人数
    public function getCountByRecordId($record_id){
        $data = $this->where(['record_id'=>$record_id])->count();

        return $data;
    }
    //获取投票比例
    public function getAvgRateByRecordIds($record_ids){
        $where['record_id']=array('in',$record_ids);
        $rows = $this->where($where)->field("record_id,AVG(rate) as rate")->group('record_id')->select();
        $rows || $rows=[];
        $data =[];
        foreach ($rows as $key=>$row){
            $data[$row['record_id']]=round($row['rate']);
        }
        return $data;
    }
}